package com.music.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.music.server.pojo.*;
import com.music.server.mapper.SingerMapper;
import com.music.server.service.CollectService;
import com.music.server.service.SingerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.music.server.service.SongService;
import com.music.server.vo.SingerVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 歌手 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-03-05
 */
@Service
public class SingerServiceImpl extends ServiceImpl<SingerMapper, Singer> implements SingerService {

    @Autowired
    private SongService songService;

    @Autowired
    private CollectService collectService;

    @Override
    public Map<String, Object> page(Integer pageNum, Integer size, SingerVo singerVo) {
        Page<Singer> singerPage = new Page<>(pageNum, size);
        QueryWrapper<Singer> singerQueryWrapper = new QueryWrapper<>();
        if (singerVo.getName() != null) {
            singerQueryWrapper.like("name", singerVo.getName());
        }
        if (singerVo.getSex() != null) {
            singerQueryWrapper.eq("sex", singerVo.getSex());
        }

        this.page(singerPage, singerQueryWrapper);
        Map<String, Object> data = new HashMap<>();
        data.put("total", singerPage.getTotal());
        data.put("list", singerPage.getRecords());
        return data;
    }

    @Transactional
    @Override
    public boolean deleteById(Integer id) {
        //删歌手
        boolean b = this.removeById(id);

        //删歌手对应的歌曲
        QueryWrapper<Song> songQueryWrapper = new QueryWrapper<>();
        songQueryWrapper.eq("singer_id", id);
        for (Song song : songService.list(songQueryWrapper)) {
            songService.deleteById(song.getId());
        }


        return true;

    }
}
